<template>
  <div class="chat-container">
    <div class="chat-header">
      <label>当前用户ID：</label>
      <input v-model="currentUserId" @change="saveUserId" placeholder="输入当前用户ID" />
      <label style="margin-left:20px;">房间号ID：</label>
      <input v-model="roomId" @change="fetchMessages" placeholder="输入房间号ID" />
      <button class="logout-btn" @click="logout">退出/切换账号</button>
    </div>
    <div class="chat-messages" ref="msgList">
      <div v-for="msg in messages" :key="msg.id" :class="['msg-row', msg.sender == currentUserId ? 'me' : 'other']">
        <div class="msg-meta">
          <span class="msg-uid">{{ msg.sender_name || '用户'+msg.sender }}</span>
          <span class="msg-time">{{ formatTime(msg.timestamp) }}</span>
        </div>
        <div :class="['bubble', msg.sender == currentUserId ? 'me-bubble' : 'other-bubble']">
          {{ msg.content }}
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input v-model="input" @keyup.enter="sendMessage" placeholder="输入消息..." :disabled="!roomId" />
      <button @click="sendMessage" :disabled="!input.trim() || !roomId">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Messages',
  data() {
    return {
      currentUserId: localStorage.getItem('userid') || '',
      roomId: '',
      messages: [],
      input: '',
      refreshTimer: null
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('auth_token');
      localStorage.removeItem('userid');
      localStorage.removeItem('user_info');
      localStorage.removeItem('access_token');
      localStorage.removeItem('retoken');
      this.$router.push('/');
    },
    saveUserId() {
      localStorage.setItem('userid', this.currentUserId);
    },
    formatTime(ts) {
      if (!ts) return '';
      const d = new Date(ts);
      return d.toLocaleString('zh-CN', { hour12: false });
    },
    async fetchMessages() {
      if (!this.roomId) return;
      try {
        const res = await axios.get(`http://127.0.0.1:8000/message/get/${this.roomId}/`);
        this.messages = (res.data.data || []).sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        this.$nextTick(this.scrollToBottom);
      } catch (e) {
        this.messages = [];
      }
    },
    async sendMessage() {
      if (!this.input.trim() || !this.roomId) return;
      try {
        const res = await axios.post(`http://127.0.0.1:8000/message/post/${this.roomId}/`, {
          content: this.input,
          room_id: Number(this.roomId),
          sender: this.currentUserId // 新增，支持自定义发送者ID
        }, {
          headers: {
            Authorization: localStorage.getItem('token') || '',
            'Content-Type': 'application/json'
          }
        });
        if (res.data && res.data.code === 200) {
          this.input = '';
          await this.fetchMessages();
        } else {
          alert('发送失败');
        }
      } catch (e) {
        alert('发送失败');
      }
    },
    scrollToBottom() {
      const el = this.$refs.msgList;
      if (el) el.scrollTop = el.scrollHeight;
    },
    startAutoRefresh() {
      this.refreshTimer = setInterval(this.fetchMessages, 3000);
    },
    stopAutoRefresh() {
      if (this.refreshTimer) clearInterval(this.refreshTimer);
      this.refreshTimer = null;
    }
  },
  mounted() {
    this.roomId = '';
    this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  }
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 700px;
  margin: 40px auto;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 24px 0 rgba(24,144,255,0.08);
  display: flex;
  flex-direction: column;
  min-height: 70vh;
}
.chat-header {
  padding: 18px 24px 0 24px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.chat-header input {
  width: 120px;
  margin-right: 10px;
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid #ddd;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px 24px 12px 24px;
  background: #f8fafc;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.msg-row {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.msg-row.me {
  align-items: flex-end;
}
.bubble {
  max-width: 320px;
  padding: 12px 18px;
  border-radius: 10px;
  font-size: 16px;
  word-break: break-all;
  position: relative;
}
.me-bubble {
  background: #95ec69;
  color: #222;
  margin-left: 40px;
}
.other-bubble {
  background: #fff;
  color: #222;
  margin-right: 40px;
  border: 1px solid #eee;
}
.msg-meta {
  font-size: 12px;
  color: #888;
  margin-bottom: 2px;
  display: flex;
  gap: 10px;
}
.chat-input {
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 10px;
}
.chat-input input {
  flex: 1;
  border: 1px solid #ccc;
  padding: 10px 16px;
  border-radius: 22px;
  font-size: 16px;
  outline: none;
  background: #f7f9fa;
}
.chat-input button {
  padding: 10px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 22px;
  font-size: 16px;
  cursor: pointer;
}
.chat-input button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
.logout-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 8px 18px;
  cursor: pointer;
  margin-left: 16px;
}
.logout-btn:hover {
  background: #ff7875;
}
</style> 